package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;


@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private RegionRepository repository;

    @Autowired
    private DestinationRepository destRepository;


    /**
     * 区域分页查询
     */
    @Override
    public Page<Region> query(RegionQuery qo) {
        // 创建查询对象
        Query query = new Query();
        // 封装条件
        // 总条数 : totalCount
        long totalCount = template.count(query, Region.class);
        if (totalCount == 0){
            // 如果总条数为0,则返回一个空的分页对象
            return Page.empty();
        }
        // 参数1:当前页(从0开始)  参数2: 每页显示条数   参数3: 排序规则    参数4: 排序列
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Region> regions = template.find(query, Region.class);

        return new PageImpl(regions,pageable,totalCount);
    }

    /**
     * 添加/修改 操作
     */
    @Override
    public void saveOrUpdate(Region region) {

        if (StringUtils.hasLength(region.getId())){
            // 如果id有长度(不为空),则表示该操作为编辑操作
            // 但需要注意的是,MongoDB的更新操作为全量更新(即对象字段和表中的列(个数)不一致时,会造成数据丢失)
            repository.save(region);
        }else{
            // 若id为空则为新增
            region.setId("");
            repository.save(region);
        }

    }

    @Override
    public void changeHotValue(String id, int hot) {
        // mongodb的更新操作为全量更新,为了防止数据丢失,需要先查再改
        Region region = repository.findById(id).orElse(null);
        region.setIshot(hot);
        repository.save(region);

    }


    @Override
    public List<Region> getHotRegion(int state) {
        List<Region> regions = repository.findByIshotOrderBySequence(state);
        return regions;
    }




}
